<?php
/*pc端客服*/
namespace app\pc\controller;

use app\admin\model\User;
use app\api\model\ChatMsg;
use app\api\model\Client;
use app\api\model\Kf;
use app\api\model\KfAssess;
use app\api\model\KfReply;
use app\api\model\MaliceIp;
use app\api\model\Users;
use app\api\model\UserTrace;
use plugin\filter;
use plugin\Gateway;
use think\Session;
use plugin\Excel;

class Index extends Common
{
    public function _initialize()
    {
        parent::_initialize();

    }

    public function index()
    {

        //登录检测
        if(!$this->check_login())
        {
            $this->login();
        }
        /**
         * 参数说明
         * get pid 聊天对象识别 enc_client_id
         */
        //关闭同个浏览器多个对话页面的客户端链接
//        $this->closeSameClient();
        $pid                = input('get.pid');
        //检查聊天对象正确性
        if(!$this->chkCurrentTarget($pid)) exit("参数错误");

        //获取聊天对象的客户端信息
        $users = $this->getUserMsg($pid);
        if(empty($users)) exit('聊天对象不存在');
        $client_user = [$users];

        //如果当前用户不是客服 并且聊天对象不是客服
        if($users['is_kf'] != 1 && !$this->isKf($this->getCurrentUserid(true))) exit('请您选择客服聊天对象');

        $photo_path = $this->config('domain')."/";

        //模板渲染
        $this->assign([
            'userPhotoOnLine' =>$photo_path .$this->config('userPhotoOnLine'),
            'userPhotoOffLine'=>$photo_path.$this->config('userPhotoOffLine'),
            'kfPhotoOnLine' =>$photo_path.$this->config('kfPhotoOnLine'),
            'kfPhotoOffLine'=>$photo_path.$this->config('kfPhotoOffLine'),
            'is_kf'     => $this->CurrentUserIsKf() ? 1 : 0,
            'client_user'=> $client_user,
            'mine'       => $this->getUserMsg($this->getCurrentUserid(true)),
            'token'      => $this->getCurrentToken(),
            'domain_ip'  => $this->config('domain_ip'),
        ]);
        return $this->fetch();
    }

    //客服不在线时，进行发送该信息
    public function sendKfOffLineText($client_id,$to_client_id)
    {
        $KfReplyModel = new KfReply();
        $reply = json_encode($KfReplyModel->total(['pageLimit'=>7]),JSON_UNESCAPED_UNICODE);
        if(empty($reply)) return;
        $userModel = new Users();
        $userInfo = $userModel->user_info(['enc_client_id'=>$to_client_id]);
        //发送7条记录
        $input = [
            'to_client_id' => $client_id,
            'type'  => 'OffLineText',
            'msg'   => $reply,
        ];
        $userModel  = new Client(array_merge($this->modelDefaultParam(),['user_id'=>$userInfo['client_id']]));
        $userModel->send_text($input);
    }


    //获取一个用户信息以及初始化在线离线
    protected function getUserMsg($client_id)
    {
        //获取客户端基本消息
        $userModel  = new Users($this->modelDefaultParam());
        $users      = $userModel->user_info(['enc_client_id'=>$client_id]);
        if(empty($users)) return null;
        //获取未查看历史记录
        $chatMsg = new ChatMsg();
        $users['no_skim'] = $chatMsg->getOneNoSkimLog($client_id,$this->getCurrentUserid(true));
        //user_id加密
        $users['client_id'] = $this->EncUserid($users['client_id']);
        //判断是否在线
        $isOnLine = $this->clientOnLine($users['client_id']);
        $users['lineState'] = $isOnLine ? "在线" : "离线";
        $users['lineStateNum'] =$isOnLine ? 1 : 0;

        return $users;
    }


    //判断一个客户端在线
    protected function clientOnLine($client_id)
    {
        $clientModel = new Client($this->modelDefaultParam());
        //在线状态，返回true，否则返回false
        return !empty($clientModel->getClientIdByUid($client_id));
    }

    //检测当前聊天对象
    protected function chkCurrentTarget($pid)
    {
        //聊天对象不得为空，并且聊天对象不能是自己
//        return !empty($pid) &&  $pid != session('user_id');
        return !empty($pid) &&  $pid != $this->getCurrentUserid(true);
    }


    //关闭同一个浏览器多个客服端页面
    protected function closeSameClient()
    {
        $clientModel = new Client($this->modelDefaultParam());
        //关闭同个浏览器另外一个聊天室链接
        $usermsg = $clientModel->getClientIdByUid($this->getCurrentUserid(true));
        if(!empty($usermsg))
        {
            $clientModel->closeClient($usermsg[0]);
        }
    }

    //绑定用户
    public function bind_user()
    {
        /**
         * 参数说明
         * post client_id 客户端id
         */
        $client_id  = input('post.client_id');

        $UserModel  = new Client($this->modelDefaultParam());
        //关闭之前的链接
        $client = $UserModel->getClientIdByUid();
        if(!empty($client) && isset($client[0]))
        {
            $UserModel->closeClient($client[0]);
        }

        $result     = $UserModel->bind_user($client_id);
        //通知所有人该用户上线
        if(isset($result['client_id']))
        $this->clientOn($result['client_id']);

        return $result;
    }

    //给用户发送消息
    public function send_text()
    {
        /**
         * 参数说明
         * post type text 为文本消息 photo 为图片消息
         * post type data 对应消息类型的内容
         * post to_client_id 对方的enc_client_id
         * post f_client_id  enc_client_id
         * post token
         * return {error,msg}
         */
        $post       = ArrRemoveJs(input('post.'));
        //token验证
        if(!isset($post['f_client_id'])
            || !isset($post['token'])  || !isset($post['to_client_id'])
            || !$this->chkToken(['enc_client_id'=>$post['f_client_id'],'token'=>$post['token']]))
        {
            if($this->CurrentUserIsKf())
            {
                return ['error'=>500,'msg'=>'客服登录超时'];
            }
            return ['error'=>1,'error'=>'错误'];
        }

        $clientModel  = new Client($this->modelDefaultParam());
        $result     = $clientModel->send_text($post);

        //检查对方是否在线
        $userModel = new Users();
        $toUserInfo = $userModel->user_info(['enc_client_id'=>$post['to_client_id']]);

        if($toUserInfo['is_kf'] == 1 && !$this->clientOnLine($post['to_client_id']))
        {
            //给当前发送人发送离线推送
            $this->sendKfOffLineText($post['f_client_id'],$post['to_client_id']);
        }

        return $result;
    }

    public function send_photo()
    {
        $post = input('post.');
        //token验证
        if(!isset($post['f_client_id'])
            || !isset($post['token']) || !isset($post['to_client_id'])
            || !$this->chkToken(['enc_client_id'=>$post['f_client_id'],'token'=>$post['token']]))
        {
            if($this->CurrentUserIsKf())
            {
                return ['error'=>500,'msg'=>'客服登录超时'];
            }
            return json_encode(['error'=>1,'msg'=>'错误'],JSON_UNESCAPED_UNICODE);
        }

        // 获取表单上传文件
        $file = request()->file('photo');
        $path =  'public' . DS . 'uploads'. DS . "chat_msg";
        if(empty($file)) return json_encode(['error'=>1,'msg'=>'没有上传图片'],JSON_UNESCAPED_UNICODE);
        $info = $file->validate(['size'=>2097152,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . $path);
        if($info){
            // 成功上传后 获取上传信息
            // 输出 jpg
            $img_path = str_replace('\\','/',$path.DS.$info->getSaveName());
            $post['type'] = 'photo';
            $post['msg']  = $this->config('domain')."/".$img_path;
            //客户端发送
            $userModel  = new Client($this->modelDefaultParam());
            $result     = $userModel->send_text($post);
            return json_encode($result,JSON_UNESCAPED_UNICODE);

        }else{
            return json_encode([
                'error' => 1,
                'msg'   => $file->getError()
            ],JSON_UNESCAPED_UNICODE);
        }
    }

    public function send_base_photo()
    {
        $post = input('post.');
        //token验证
        if(!isset($post['f_client_id'])
            || !isset($post['token']) || !isset($post['to_client_id'])
            || !$this->chkToken(['enc_client_id'=>$post['f_client_id'],'token'=>$post['token']]))
        {
            if($this->CurrentUserIsKf())
            {
                return ['error'=>500,'msg'=>'客服登录超时'];
            }
            return json_encode(['error'=>1,'msg'=>'错误'],JSON_UNESCAPED_UNICODE);
        }


        $img = $post['image'];
        $path[0] = './uploads';
        $path[1] = "/chat_msg";
        $path[2] = $path[0].$path[1]."/".date('Ymd');
        $type_limit = array('jpg','jpeg','png');

        if(preg_match('/data:\s*image\/(\w+);base64,/iu',$img,$tmp)){
            if(!in_array($tmp[1],$type_limit)){
                $res["error"] = 2;
                $res["msg"] = "图片错误";
                return $res;
            }
        }else{
            $res["error"] = 3;
            $res["msg"] = "图片错误";
            return $res;
        }

        $img = str_replace(' ','+',$img);
        $img = str_replace($tmp[0], '', $img);
        $img = base64_decode($img);

        $file_name = md5($post['f_client_id'].time()).'.'.$tmp[1];
        $file = $path[2]."/".$file_name;
        if(!is_dir($path[0])) mkdir($path[0],0777);
        if(!is_dir($path[0].$path[1])) mkdir($path[0].$path[1],0777);
        if(!is_dir($path[2])) mkdir($path[2],0777);
        if(!file_put_contents($file,$img)){
            $res["error"] = 1;
            $res["msg"] = "图片错误";
            return $res;
        }else{
            $post['type'] = 'photo';
            $post['msg']  = $this->config('domain')."/"."public/".str_replace('./',"",$file);
            //客户端发送
            $userModel  = new Client($this->modelDefaultParam());
            $result     = $userModel->send_text($post);
            return json_encode($result,JSON_UNESCAPED_UNICODE);
        }

    }

    //获取最近的聊天记录
    public function getLateMsg()
    {
        /**
         * 参数说明
         * post to_client_id        当前对话的enc_client_id
         * post f_client_id  操作者enc_client_id
         * post token       token令牌
         * post msgid  最早对话的msgid，获取比这个消息id更小的id即更早的消息记录
         *
         */
        $post = input('post.');
        //token验证
        if(!isset($post['f_client_id'])
            || !isset($post['token'])
            || !$this->chkToken(['enc_client_id'=>$post['f_client_id'],'token'=>$post['token']]))
        {
            if($this->CurrentUserIsKf())
            {
                return ['error'=>500,'msg'=>'客服登录超时'];
            }
            return ['error'=>1,'msg'=>'错误'];
        }
        $MsgModel = new ChatMsg($this->modelDefaultParam());
        $log = $MsgModel->getlog($this->getCurrentUserid(true),$post['to_client_id'],$post['msgid']);
        //客户端给当前用户发送历史消息
        $clientModel = new Client($this->modelDefaultParam());
        $clientModel->sendOneUser(['type'=>'history','msg'=>$log,'client_id'=>$post['to_client_id']],$this->getCurrentUserid(true));
    }


    //获取最近聊天的用户列表
    public function getLateUser()
    {
        /**
         * 参数说明
         * post.f_client_id  对方的client_id 即数据库中的enc_client_id
         * post.token       [如果client_id是客服账号，则无需该参数]当前用户请求的合法token
         */
        $input = input('post.');
        //验证参数以及该用户是否在线状态
        if(
            !isset($input['f_client_id'])
            || !isset($input['token'])
            || !$this->clientOnLine($input['f_client_id'])
        )
        {
            return ['error'=>'1','msg'=>"非法操作"];
        }

        $msgModel = new ChatMsg();
        $userModel = new Users();
        $clientModel= new Client();

        //获取用户
        if(!$info = $userModel->user_info(['enc_client_id'=>$input['f_client_id']])){ return ['error'=>1,'非法操作']; };
        //检查token，并加载数据
        if($this->chkToken(['token'=>$input['token'],'enc_client_id'=>$input['f_client_id']]))
        {
            //发联系列表通过soket发送
            $data = $msgModel->getLogUser($input['f_client_id']);
            //每个人在线状态
            foreach($data as $k=>$v)
            {
                $data[$k]['lineState'] = $this->isClientOnLine($v['enc_client_id']) ? 1 : 0;
            }
            $clientModel->sendOneUser(['type'=>'userList','msg'=>['data'=>$data,'is_kf'=>1]],$input['f_client_id']);
            return ['error'=>0,'获取完毕'];
        }
        else
        {
            return ['error'=>1,'非法操作'];
        }

    }

    //自动回复请求
    public function autoReply()
    {

        /**
         * 参数说明
         * post type text 为文本消息 photo 为图片消息
         * post type data 对应消息类型的内容
         * post to_client_id 对方的enc_client_id
         * post f_client_id  enc_client_id
         * post token
         * return {error,msg}
         */
        $post       = input('post.');
        //token验证
        if(!isset($post['id'])
            ||!isset($post['f_client_id'])
            || !isset($post['token'])  || !isset($post['to_client_id'])
            || !$this->chkToken(['enc_client_id'=>$post['f_client_id'],'token'=>$post['token']]))
        {
            if($this->CurrentUserIsKf())
            {
                return ['error'=>500,'msg'=>'客服登录超时'];
            }
            return ['error'=>1,'error'=>'错误'];
        }
        $ReplyModel = new KfReply();
        $data = $ReplyModel->info(['id'=>$post['id']]);
        $userModel = new Users();
        $ToClient = $userModel->user_info(['enc_client_id'=>$post['to_client_id']]);

        if(!empty($data))
        {
            //把对话方式对换
            $post['to_client_id'] = $post['f_client_id'];

            $data['content'] = urldecode($data['content']);
            $post['type'] = 'text';
            $post['msg'] = "
                问题：<span style='color:#0099ff'>{$data['title']} </span><br>
                {$data['content']}
            ";
            $userModel  = new Client(['user_id'=>$ToClient['client_id'],'user_name'=>$ToClient['nickname'],'nickname'=>$ToClient['nickname'],'isKf'=>$ToClient['is_kf']]);
            $result     = $userModel->send_text($post);
        }
        return $result;
    }

    //客服对服务评价
    public function assess()
    {
        $post = input('post.');
        $post = array_merge(['cent'=>"",'tid'=>""],$post);

        if(empty($post['tid'])) return ['error'=>1,'msg'=>"未指定客服"];

        $KfModel = new Kf();
        $kfInfo = $KfModel->info(['enc_client_id'=>$post['tid']]);
        if(empty($kfInfo)) return ['error'=>1,'msg'=>"不存在该客服"];
        $post['kf_id'] = $kfInfo['kf_id'];
        $post['client_id'] = $this->getCurrentUserid(false);
        $KfAssessModel = new KfAssess();
        $result =  $KfAssessModel->add($post);
        if($result['error'] == 0)
        {
            $clientModel  = new Client($this->modelDefaultParam());
            $clientModel->send_text(['msg'=>"已评价，谢谢您优质的服务",'type'=>'text','to_client_id'=>$post['tid'],'client_name'=>""]);
        }

        return $result;
    }


    //添加ip连接追踪记录
    public function trace()
    {
        /**
         * 参数说明
         * 接口地址 /public/index.php/pc/index/trace
         * post.url
         * post.info
         */
        $ip = empty(cookie('kfip')) && strlen(cookie('ip')) != 40 ? sha1(real_ip().randString(15)) : cookie('kfip');

        cookie('kfip',$ip);

        $input = input('post.');
        $input['ip'] = $ip;
        $traceModel = new UserTrace();
        $result =  $traceModel->add($input);
        if($result['error'] != 0)
        {
            return $result;
        }
        //根据ip获取当前用户信息
        $userModel = new Users();

        $user = $userModel->user_info(['ip'=>$ip]);
        if(empty($user))
        {
            return $result;
        }

        $MsgModel = new ChatMsg();
        $allKf = $MsgModel->getUserConnectKfClientId($user['enc_client_id']);

        if(empty($allKf)) return $result;
        $clientModel = new Client();
        //给与之联系的客服都发送追踪消息
        foreach($allKf as $v)
        {
            $clientModel->sendOneUser([
                'type'  => 'text',
                'time'  => date('m-d H:i:s',time()),
                'msg'   => base64_encode("用户追踪：<br> <a style='color: #00a0e9' target='_blank' href='".$input['url']."'>".$input['url']."</a> <br> ".strip_tags($input['info'])),
                'client_id' => $user['enc_client_id'],
                'client_name'=> $user['nickname'],
                'is_html_out'=> 1,
                'is_kf'     => 0
            ],$v);
        }
        return $result;
    }

    //获取该用户ip连接追踪记录
    public function getTrace()
    {
        /**
         * 参数说明
         * post.client_id  用户加密的client_id
         */
        //登录检测
        if(!$this->check_login())
        {
            return ['error'=>1,'msg'=>'未登录'];
        }
        //如果不是客服，则无法获取
        if(!$this->isKf($this->getCurrentUserid(true)))
        {
            return ['error'=>1,'msg'=>"非法操作"];
        }
        $input = input('post.');
        $userModel  = new Users($this->modelDefaultParam());
        $users      = $userModel->user_info(['enc_client_id'=>$input['client_id']]);
        if(empty($users))
        {
            return ['error'=>1,"msg"=>'不存在该用户'];
        }
        $traceModel = new UserTrace();
        $data = [
            'error'=> 0,
            'data' => $traceModel->getToday(['ip'=>$users['ipcookie']])
        ];

        return $data;
    }

    //申请封禁ip
    public function banIp()
    {
        //登录检测
        if(!$this->check_login())
        {
            return ['error'=>1,'msg'=>'未登录'];
        }
        //如果不是客服，则无法获取
        if(!$this->isKf($this->getCurrentUserid(true)))
        {
            return ['error'=>1,'msg'=>"非法操作"];
        }

        $ip = input('post.ip');
        $MaliceModel = new MaliceIp();
        $MaliceModel->add($ip);
        return  ['error'=>0,'msg'=>"禁止完成，即将关闭当前的聊天窗口"];
    }

    public function export()
    {
        $data = json_decode(file_get_contents('./video.txt'),true);
        $export = [
            'file_name' => "商品视频",
            'ex_title'  => "商品视频 ",
            'data'      => $data,
            'ex_th'     =>['goods_name'=>"商品名字",'goods_desc'=>"视频地址"]
        ];
        $excel = new Excel($export);
        $excel->export();
    }
}